import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ConfigService } from '@nestjs/config';
import { BaseService } from '@wwjCommon/base/base.service';
import { CacheService } from '@wwjCommon/cache/cache.service';
import { LoggingService } from '@wwjCommon/logging/logging.service';
import { UploadService } from '@wwjVendor/upload/upload.service';
import { PayService } from '@wwjVendor/pay/pay.service';
import { SmsService } from '@wwjVendor/sms/sms.service';
import { NoticeService } from '@wwjVendor/notice/notice.service';

@Injectable()
export class CoreWapTraitService extends BaseService<any> {
  private readonly logger = new Logger(CoreWapTraitService.name);

  constructor(
    @InjectRepository(Object)
    protected readonly repository: Repository<any>,
    private readonly cacheService: CacheService,
    private readonly configService: ConfigService,
    private readonly loggingService: LoggingService,
    private readonly uploadService: UploadService,
    private readonly payService: PayService,
    private readonly smsService: SmsService,
    private readonly noticeService: NoticeService,
  ) {
    super(repository);
  }

  /**
   * compileDiyComponentsCode
   * 对应 PHP: WapTrait_core::compileDiyComponentsCode()
   * 逻辑类型: undefined - undefined
   */
  async compileDiyComponentsCode(compile_path: any, addon: any) {
    // 基于PHP真实逻辑: compileDiyComponentsCode
    // PHP原文: $content = "<template>\n";         $content .= "    <view class=\"diy-group\" id=\"componentList\">\n";         $content .= "        <top-tabbar :scro...
const content = "<template>\n";
        content  +=  "    <view class=\"diy-group\" id=\"componentList\">\n";
        content  +=  "        <top-tabbar :scrollBool=\"diyGroup.componentsScrollBool.TopTabbar\" v-if=\"data.global && Object.keys(data.global).length && data.global.topStatusBar && data.global.topStatusBar.isShow\" ref=\"topTabbarRef\" :data=\"data.global\" />\n";
        content  +=  "        <pop-ads v-if=\"data.global && Object.keys(data.global).length && data.global.popWindow && data.global.popWindow.show\" ref=\"popAbsRef\" :data=\"data.global\" />\n";
        content  +=  "        <template v-for=\"(component, index) in data.value\" :key=\"component.id\">\n";
        content  +=  "           <view v-show=\"component.componentIsShow\"\n";
        content  +=  "               @click=\"diyStore.changeCurrentIndex(index, component)\"\n";
        content  +=  "               :class=\"diyGroup.getComponentClass(index,component)\" :style=\"component.pageStyle\">\n";
        content  +=  "                <view class=\"relative\" :style=\"{ marginTop : component.margin.top < 0 ? (component.margin.top * 2) + 'rpx' : '0', marginBottom : component.margin.bottom < 0 ? (component.margin.bottom * 2) + 'rpx' : '0' }\">\n";
        content  +=  "                   <!-- 装修模式下，设置负上边距后超出的内容，禁止选中设置 -.\n";
        content  +=  "                    <view v-if=\"diyGroup.isShowPlaceHolder(index,component)\" class=\"absolute w-full z-1\" :style=\"{ height : (component.margin.top * 2 * -1) + 'rpx' }\" @click.stop=\"diyGroup.placeholderEvent\"></view>\n";

        const root_path = compile_path . str_replace('/', DIRECTORY_SEPARATOR, 'app/components/diy']; // 系统自定义组件根目录
        const file_arr = getFileMap(root_path);

        if (!!file_arr)) {
            foreach (file_arr as ck => cv) {
                if (str_contains(cv, 'index.vue')) {

                    const path = str_replace(root_path  + '/', '', ck];
                    const path = str_replace('/index.vue', '', path);
                    if (path == 'group') {
                        continue;
                    }

                    // 获取自定义组件 key 关键词
                    const name_arr = explode('-', path);
                    foreach (name_arr as k => v) {
                        // 首字母大写
                        name_arr[ k ] = strtoupper(v[ 0 ) || '') . substr(v, 1];
                    }
                    const name = implode('', name_arr);
                    const file_name = 'diy-' . path;

                    content  +=  "                <template v-if=\"component.componentName == '{name}'\">\n";
                    const event_str = 'event';
                    content  +=  "                   <file_name ref=\"diy{name}Ref\" :component=\"component\" :global=\"data.global\" :index=\"index\" :scrollBool=\"diyGroup.componentsScrollBool.{name}\" @update:componentIsShow=\"component.componentIsShow = {event_str}\" />\n";
                    content  +=  "                </template>\n";
                }
            }
  }

  /**
   * installPageCode
   * 对应 PHP: WapTrait_core::installPageCode()
   * 逻辑类型: undefined - undefined
   */
  async installPageCode(compile_path: any) {
    // 基于PHP真实逻辑: installPageCode
    // PHP原文: if (!file_exists($this->geAddonPackagePath($this->addon) . 'uni-app-pages.php')) return;          $uniapp_pages = require $this->geAddonPackagePath($t...
if (!file_exists(this.geAddonPackagePath(this.addon)  + 'uni-app-pages.php')) return;

        const uniapp_pages = require this.geAddonPackagePath(this.addon)  + 'uni-app-pages.php';

        if (!uniapp_pages[ 'pages' ))) {
            return;
  }

  /**
   * uninstallPageCode
   * 对应 PHP: WapTrait_core::uninstallPageCode()
   * 逻辑类型: undefined - undefined
   */
  async uninstallPageCode(compile_path: any) {
    // 基于PHP真实逻辑: uninstallPageCode
    // PHP原文: if (!file_exists($this->geAddonPackagePath($this->addon) . 'uni-app-pages.php')) return;          $uniapp_pages = require $this->geAddonPackagePath($t...
if (!file_exists(this.geAddonPackagePath(this.addon)  + 'uni-app-pages.php')) return;

        const uniapp_pages = require this.geAddonPackagePath(this.addon)  + 'uni-app-pages.php';

        if (!uniapp_pages[ 'pages' ))) {
            return;
  }

  /**
   * compileLocale
   * 对应 PHP: WapTrait_core::compileLocale()
   * 逻辑类型: undefined - undefined
   */
  async compileLocale(compile_path: any, addon: any) {
    // 基于PHP真实逻辑: compileLocale
    // PHP原文: $locale_data = [];          $root_path = $compile_path . str_replace('/', DIRECTORY_SEPARATOR, 'locale'); // 系统语言包根目录         $file_arr = getFileMap($...
const locale_data = [];

        const root_path = compile_path . str_replace('/', DIRECTORY_SEPARATOR, 'locale'); // 系统语言包根目录
        const file_arr = getFileMap(root_path, [)];
        if (!!file_arr)) {
            foreach (file_arr as ck => cv) {
                if (str_contains(cv, '.json')) {
                    const app_json = @file_get_contents(ck];
                    const json = json_decode(app_json, true);
                    // 清空当前安装/卸载的插件语言包
                    foreach (json as jk => jc) {
                        if (String.prototype.indexOf.call(jk, addon) !== false) {
                            unset(json[ jk )];
                        }
                    }
                    locale_data[ cv ] = [
                        path: ck,
                        json: json
                    ;
  }
  }

  /**
   * mergeManifestJson
   * 对应 PHP: WapTrait_core::mergeManifestJson()
   * 逻辑类型: undefined - undefined
   */
  async mergeManifestJson(compile_path: any[], merge_data: any[]) {
    // 基于PHP真实逻辑: mergeManifestJson
    // PHP原文: $manifest_json = str_replace('/', DIRECTORY_SEPARATOR, $compile_path . 'src/manifest.json');         $manifest_content = $this->jsonStringToArray(file...
const manifest_json = str_replace('/', DIRECTORY_SEPARATOR, compile_path  + 'src/manifest.json');
        const manifest_content = this.jsonStringToArray(file_get_contents(manifest_json)];
        ( this.coreAddonBaseService ).writeArrayToJsonFile(array_merge2(manifest_content, merge_data), manifest_json];
    }

    /**
     * json 字符串解析成数组
     * @param string
     * @return */
    private async jsonStringToArray(string)
    {
        const list = explode("\n", string];
        const json_ = [);
        foreach (list as index => item) {
            if (String.prototype.indexOf.call(item, '/*') === false) {
                json_array[] = item;
            }
  }

  /**
   * jsonStringToArray
   * 对应 PHP: WapTrait_core::jsonStringToArray()
   * 逻辑类型: undefined - undefined
   */
  async jsonStringToArray(stringParam: string) {
    // 基于PHP真实逻辑: jsonStringToArray
    // PHP原文: $list = explode("\n", $string);         $json_array = [];         foreach ($list as $index => $item) {             if (strpos($item, '/*') === false) ...
const list = explode("\n", string];
        const json_ = [);
        foreach (list as index => item) {
            if (String.prototype.indexOf.call(item, '/*') === false) {
                json_array[] = item;
            }
  }
}
